
jQuery.extend({
	

    createUploadIframe: function(id, uri)
	{
			//create frame
            var frameId = 'jUploadFrame' + id;
            var iframeHtml = '<iframe id="' + frameId + '" name="' + frameId + '" style="position:absolute; top:-9999px; left:-9999px"';
			if(window.ActiveXObject)
			{
                if(typeof uri== 'boolean'){
					iframeHtml += ' src="' + 'javascript:false' + '"';

                }
                else if(typeof uri== 'string'){
					iframeHtml += ' src="' + uri + '"';

                }	
			}
			iframeHtml += ' />';
			jQuery(iframeHtml).appendTo(document.body);

            return jQuery('#' + frameId).get(0);			
    },
    createUploadForm: function(id, fileElementId, data)
	{
		//create form	
		var formId = 'jUploadForm' + id;
		var form = jQuery('<form  action="" method="POST" name="' + formId + '" id="' + formId + '" enctype="multipart/form-data"></form>');	
		if(data)
		{
			for(var i in data)
			{
				if (typeof(data[i]) == "object") {
					var ndata = data[i];
					for (var j = 0; j < ndata.length; j++) {
						for(var key in ndata[j]) {
							jQuery('<input type="hidden" name="' + key + '" value="' + ndata[j][key] + '" />').appendTo(form);
						}
					}
				} else {
					if (i == 'video_url') {
						var tmp = '<textarea style="display: none;" name="video_url" rows="5" cols="50">' + data[i] +'</textarea>';
						jQuery(tmp).appendTo(form);
					} else {
						jQuery('<input type="hidden" name="' + i + '" value="' + data[i] + '" />').appendTo(form);
					}
					
				}
			}			
		}		
		
		if (fileElementId instanceof Array) {
			for (var i = 0; i < fileElementId.length; i ++) {
	            var oldElement = jQuery('#' + fileElementId[i]);
	            var newElement = jQuery(oldElement).clone();
	            jQuery(oldElement).attr('id', fileElementId[i]);  
	            jQuery(oldElement).attr('name', fileElementId[i]);
	            jQuery(oldElement).before(newElement);
	            jQuery(oldElement).appendTo(form);
	        }
		} 
		else {
			var fileId = 'jUploadFile' + id;
			var oldElement = '';
			if(typeof(fileElementId) == 'string'){
				oldElement = jQuery('#' + fileElementId);
			}else{
				oldElement = fileElementId;
			}
			var newElement = jQuery(oldElement).clone();
			jQuery(oldElement).attr('id', fileId);
			jQuery(oldElement).before(newElement);
			jQuery(oldElement).appendTo(form);
		}
		
		//set attributes
		jQuery(form).css('position', 'absolute');
		jQuery(form).css('top', '-1200px');
		jQuery(form).css('left', '-1200px');
		jQuery(form).appendTo('body');		
		return form;
    },

    ajaxFileUpload: function(s) {
    	function showSuccess(){
    		clearInterval(timer);
    		$('.progress .text').text('上传成功');
			$('.progress .percentage').css('width', '100%');
			timer = setTimeout(function(){
				$('.progress').hide();
    			$('.progress .text').text('1%');
    			$('.progress .percentage').css('width', '1%');
				clearTimeout(timer);
			}, 2000);
    	}
        // TODO introduce global settings, allowing the client to modify them for all requests, not only timeout		
        s = jQuery.extend({}, jQuery.ajaxSettings, s);
        var id = new Date().getTime()  ;
        // 用于模拟上传
        var timer= 0;
		var fielName = '';
		var filess = '';
		var fileParent = '';
		if(typeof(s.fileElementId) == 'string'){
			fielName = $('#' + s.fileElementId).val(); 
			filess = $('#' + s.fileElementId);
		}else{
			fielName =s.fileElementId.val();
			filess = s.fileElementId;
		}
		fileParent = filess.parent();
		function isEmpty(s){
			return s == null || s == '' || s == undefined || s == 'null';
		}; 
		if(isEmpty(fielName)){
			s.error('上传失败，请选择需要上传的文件！');
			return false;
		}
		if(fielName.indexOf('%')>-1){
			s.error('上传失败，文件名中不能出现%！');
			return false;
		}
	    var extention = fielName.substring(fielName.lastIndexOf(".") + 1).toLowerCase(); 
	    var fileTrueName = fielName.substring( fielName.lastIndexOf('\\')+1 ,
	    		fielName.lastIndexOf("."));
	    function judgeType(){
		    var typeList = s.fileFilter.split(',');
		    for(var i in typeList){
		    	if(typeList[i].toLowerCase().indexOf(extention) >= 0){
		    		return true;
		    	}
		    	if(parseInt(i) >= (typeList.length-1)){
		    		return false;
		    	}
		    }
	    }
	    if(s.fileFilter && !judgeType()){
    		s.error('上传失败，文件类型不是'+s.fileFilter );
    		return false;
	    } 
	    if(!s.nameLength){
	    	s.nameLength = 20;
	    }
	    function strlen(str){
	        var len = 0;
	        for (var i=0; i<str.length; i++) { 
	         var c = str.charCodeAt(i); 
	        //单字节加1 
	         if ((c >= 0x0001 && c <= 0x007e) || (0xff60<=c && c<=0xff9f)) { 
	           len++; 
	         } 
	         else { 
	          len+=2; 
	         } 
	        } 
	        return len;
	    }
		if(strlen(fileTrueName)>s.nameLength){
			s.error("上传失败，当前文件名长度大于" + s.nameLength + "！");
			return false;
		}
	    //文件大小限制  
	    if (!s.fileSize){
	    	s.fileSize = 8 * 1024;
	    	
	    }
	    function fileSize(){
	      var fs = 0;  
	      try {  
	        if (window.ActiveXObject) {  
	          //IE浏览器  
	          var image = new Image();  
	          image.dynsrc = fielName;  
	          fs = image.fileSize;  
	        } else {  
	          fs = filess[0].files[0].size;  
	        }  
	      } catch(e) {
	      }  
	      if (fs > s.fileSize*1024) {  
	    	  if(s.fileSize/1024/1024>0){
	    		  s.error("上传失败，当前文件大小 (" + parseInt(fs/1024/1024) + "MB) 超过允许的限制值 (" + s.fileSize/1024 +"KB)！");
	    	  }
	    	  s.error("上传失败，当前文件大小 (" + parseInt(fs/1024) + "KB) 超过允许的限制值 (" + s.fileSize +"KB)！");
	    	  return false;
	      } 
	      return true;
	    } 
	    if(!fileSize()){
	    	return false;
	    }
		var form = jQuery.createUploadForm(id, s.fileElementId, (typeof(s.data)=='undefined'?false:s.data));
		var io = jQuery.createUploadIframe(id, s.secureuri);
		var frameId = 'jUploadFrame' + id;
		var formId = 'jUploadForm' + id;
        // Watch for a new set of requests
        if ( s.global && ! jQuery.active++ )
		{
			jQuery.event.trigger( "ajaxStart" );
		}            
        var requestDone = false;
        // Create the request object
        var xml = {}   
        if ( s.global ){
        	if(fileParent.find('.progress').length<=0){
        		fileParent.append('<div class="progress">' +
            			'<span class="text">1%</span>' +
            			'<span class="percentage" style="width: 1%;"></span>' +
            			'</div>');
        	}else{
    			$('.progress .text').text('1%');
    			$('.progress .percentage').css('width', '1%');
        	}
			$('.progress').show();
        	timer = setInterval(function(){
        		var progressVal = parseInt($('.progress .text').text()) + 1;
        		if(progressVal<=100){
        			$('.progress .text').text(progressVal + '%');
        			$('.progress .percentage').css('width', progressVal + '%');
        		}else{
        			clearInterval(timer);
        		}
        	}, 2000);
            jQuery.event.trigger("ajaxSend", [xml, s]);
        }
        // Wait for a response to come back
        var uploadCallback = function(isTimeout)
		{			
			var io = document.getElementById(frameId);
            try 
			{				
				if(io.contentWindow)
				{
					 xml.responseText = io.contentWindow.document.body?io.contentWindow.document.body.innerHTML:null;
                	 xml.responseXML = io.contentWindow.document.XMLDocument?io.contentWindow.document.XMLDocument:io.contentWindow.document;
					 
				}else if(io.contentDocument)
				{
					 xml.responseText = io.contentDocument.document.body?io.contentDocument.document.body.innerHTML:null;
                	xml.responseXML = io.contentDocument.document.XMLDocument?io.contentDocument.document.XMLDocument:io.contentDocument.document;
				}						
            }catch(e)
			{
            	clearInterval(timer);
    			$('.progress').hide();
				//jQuery.handleError(s, xml, null, e);
			}
            if ( xml || isTimeout == "timeout") 
			{				
                requestDone = true;
                var status;
                var data;
                try {
                    status = isTimeout != "timeout" ? "success" : "error";
                    // Make sure that the request was successful or notmodified
                    if ( status != "error" )
					{
                        // process the data (runs the xml through httpData regardless of callback)
                         data = jQuery.uploadHttpData( xml, s.dataType );    
                        // If a local callback was specified, fire it and pass it the data
                        if ( s.success ){
                        	showSuccess();
                        	/*上传文件功能增加非空判断*/
                        	var dataList = data.split(',').length > 1 ? 
                        			data.split(','): data.split('|');
                        	if(dataList[0] && dataList[1] && (
                        			dataList[0].toString() == 'null'
                        		|| dataList[1].toString() == 'null')){
                                s.error('上传服务器失败！');
                                return false;
                        	}
                        	/*上传文件功能增加非空判断*/
                        	s.success( data, status );
                        }
    
                        // Fire the global callback
                        if( s.global ){
                        	showSuccess();
                            jQuery.event.trigger( "ajaxSuccess", [xml, s] );
                        }
                    } else{
                    	clearInterval(timer);
            			$('.progress').hide();
                    }
                    //else
                        //jQuery.handleError(s, xml, status);
                } catch(e) 
				{
                    status = "error";
                	clearInterval(timer);
        			$('.progress').hide();
                    //jQuery.handleError(s, xml, status, e);
                   // s.error(data, status,e );
                }

                // The request was completed
                if( s.global )
                    jQuery.event.trigger( "ajaxComplete", [xml, s] );

                // Handle the global AJAX counter
                if ( s.global && ! --jQuery.active ){
//                	clearInterval(timer);
//        			$('.progress').hide();
                    jQuery.event.trigger( "ajaxStop" );
                }

                // Process result
                if ( s.complete )
                    s.complete(xml, status);

                jQuery(io).unbind()

                setTimeout(function()
									{	try 
										{
											jQuery(io).remove();
											jQuery(form).remove();	
											
										} catch(e) 
										{
						                	clearInterval(timer);
						        			$('.progress').hide();
											//jQuery.handleError(s, xml, null, e);
										}									

									}, 100)

                xml = null

            }
        }
        // Timeout checker
        if ( s.timeout > 0 ) 
		{
            setTimeout(function(){
                // Check to see if the request is still happening
                if( !requestDone ) uploadCallback( "timeout" );
            }, s.timeout);
        }
        try 
		{

			var form = jQuery('#' + formId);
			jQuery(form).attr('action', s.url);
			jQuery(form).attr('method', 'POST');
			jQuery(form).attr('target', frameId);
            if(form.encoding)
			{
				jQuery(form).attr('encoding', 'multipart/form-data');      			
            }
            else
			{	
				jQuery(form).attr('enctype', 'multipart/form-data');			
            }			
            jQuery(form).submit();

        } catch(e) 
		{			
        	clearInterval(timer);
			$('.progress').hide();
            //jQuery.handleError(s, xml, null, e);
        }
		
		jQuery('#' + frameId).load(uploadCallback	);
        return {abort: function () {}};	

    },

    uploadHttpData: function( r, type ) {
        var data = !type;
        data = type == "xml" || data ? r.responseXML : r.responseText;
        
        // If the type is "script", eval it in global context
        if (type == "script") {
            jQuery.globalEval(data);
        } else if (type == "json" || type == "JSON") {// Get the JavaScript object, if JSON is used.
            var rx = new RegExp("<pre.*?>(.*?)</pre>","i");
            var am = rx.exec(data);
            //this is the desired data extracted
            data = am != null ? am[1] : data;    //the only submatch or itself
            eval( "data = " + data );
        } else if (type == "html")// evaluate scripts within html
            jQuery("<div>").html(data).evalScripts();
        return data;
    }
})

